package com.lagou;

/**Java编程写一个会导致死锁的程序
 *
 *
 * 开两个线程 Thread-0 和 Thread-1
 * 两个线程共同持有两个Object 对象
 *
 */
public class DeadLockTest implements Runnable {

    // 锁的标志
    private int flag;


    public DeadLockTest(int flag) {
        this.flag = flag;
    }

    // 两个线程里面共同持有两个Object对象：obj0和 obj1。这两个对象 作为同步代码块的锁；
    // 两个对象是 类级别的  加上static 来修饰
    static Object obj0 = new Object();
    static Object obj1 = new Object();


    @Override
    public void run() {

        System.out.println("当前锁的标志 ：" + flag);

        if (flag == 0) {
            synchronized (obj0) {
                try {
                    // 防止线程 启动  一下子就连续获得了obj0和 obj1 两个对象的对象锁
                    System.out.println("线程：" + Thread.currentThread().getName() + "已获得锁" + obj0);
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("线程：" + Thread.currentThread().getName() + "等待获得锁" + obj1);

                synchronized (obj1) {
                    System.out.println("线程：" + Thread.currentThread().getName() + "已获得锁" + obj1);
                }
            }
        }


        if (flag == 1) {
            synchronized (obj1) {
                try {
                    System.out.println("线程：" + Thread.currentThread().getName() + "已获得锁" + obj1);
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println("线程：" + Thread.currentThread().getName() + "等待获得锁" + obj0);
                synchronized (obj0) {
                    System.out.println("线程：" + Thread.currentThread().getName() + "已获得锁" + obj0);
                }
            }
        }


    }



    public static void main(String[] args) {
        // 两个线程
        Thread thread0 = new Thread( new DeadLockTest(0));
        Thread thread1 = new Thread(new DeadLockTest(1));

        // 两个线程的启动
        thread0.start();
        thread1.start();
    }



}

